<?php
header("Content-type:text/html;charset=utf-8");
Class userAction extends commonAction{
/************************************初始化*****************************************/	
	private $user;
	private $diqudaima;
	private $address;
	private $order;
	private $product;
	private $bank;
	private $consign;
	private $consign_img;
	private $favorite;
	private $brand;
	private $shop_cart;
	private $coupon;
	private $wallet;
	private $transfer;

    function __construct()
    {
        parent::__construct();
        $this->user = D('user');
        $this->diqudaima = D('diqudaima');
        $this->address = D('address');
        $this->order = D('order');
        $this->product = D('product');
        $this->bank = D('bank');
        $this->consign = D('consign');
        $this->consign_img = D('consign_img');
        $this->favorite = D('favorite');
        $this->brand = D('brand');
        $this->shop_cart = D('shop_cart');
        $this->coupon = D('coupon');
        $this->wallet = D('wallet');
        $this->transfer = D('transfer');
    }

/************************************初始化*****************************************/
    
/***********************************个人中心开始******************************************/
    //个人中心展示页面
	public function center()
	{
		$OK = $_GET['ok'];
		$id = $_SESSION['id'];
		$val = $this->user->where(array('id'=>$id))->select();
        if(empty($val[0]['password']))
        {
            $val[0]['set_pass']='block';
        }else{
            $val[0]['set_pass']='none';
        }
		// p($val);
		$email = $this->user->where('status=1 AND id='.$id)->getField('email');
		$info = explode(" ", $val[0]['address']);
		$this->assign('email',$email);
		$this->assign('address',$info);
		$this->assign('data',$val[0]);
		$this->assign('ok',$OK);
		$this->assign('id',$id);
		$this->display();
		
	}
	
	
	
/***********************************个人中心结束******************************************/

/***********************************优惠券************************************/
	// public function card(){
	// 	C('LAYOUT_ON',false);
	// 	$this->display();
	// }

	public function card(){
		if (IS_POST) {
			// p($_POST);
		}else{
			C('LAYOUT_ON',false);
			$coupon = $this->coupon->where('uid='.$_SESSION['id'])->select();
			
			// $luck = $this->user->where('id='.$_SESSION['id'])->getField('luck');
			// $data = D('luck')->where('luck='.$luck)->find();
			$this->assign('coupon',$coupon);
			// $this->assign('luck',$luck);
			// $this->assign('data',$data);
			$this->display();	
		}
		
	}
/***********************************优惠券************************************/

/************************************购物车开始*******************************************/


	//购物车新
	public function mycart()
		{
		C('LAYOUT_ON',false);
		$_SESSION['url']= $_SERVER['REQUEST_URI'];
		$uid = $_SESSION['id'];
		$cart = $this->shop_cart->where('user_id='.$uid)->select(); //查看购物车的商品
		
       
        /**********************************************************/

        /************************拿到购物车中商品的ID********************************/
        $data = $this->shop_cart->where('user_id='.$uid)->select();
		$allPayProduct=array();
        foreach($data as $val)
        {
            $allPayProduct[] = $val['product_id'];       //  购物车中的id
        }
        /*************************拿到购物车中商品的ID*******************************/
        $num=count($allPayProduct); // 计算出商品总数

        $id=array_unique(array_unique($allPayProduct));//去掉重复的商品ID
        $allPayID = implode(",",$id); //所有支付ID格式化为字符串


        $map['id']  = array('in',$allPayID);
        $product = $this->product->where($map)->select();//查找id在购物车上的商品

		$allPrice = ''; 							   //得出购物车上商品的总价
		foreach ($product as $val) {	
		 	$allPrice += $val['shop_price'];
		 } 

		 /*****第一次下单优惠*****/
		 $first = $this->order->where('uid='.$uid)->count();
		 if ($first==0) {
		 	if ($allPrice>=5000) {
		 		$sumRealPrice=$allPrice-500;
                $firstDeal="500";//满5000以上减去500	
		 	}elseif($allPrice>=3000&&$allPrice<5000){
		 		$sumRealPrice=$allPrice-200;
                $firstDeal="200";//满3000少于5000减去200
		 	}else{
		 		$sumRealPrice=$allPrice;
                $firstDeal="off";
		 	}
		 }else{
		 	$sumRealPrice=$allPrice;
            $firstDeal="off";
		 }
		  // p($sumRealPrice);
		 // die();
		 /*****第一次下单优惠*****/
		 
        /**********************************************************/
        $this->assign('sumRealPrice',$sumRealPrice);
        $this->assign('firstDeal',$firstDeal);
        
        $this->assign('cart',$cart);
        $this->assign('sumPrice',$allPrice);
        $this->assign('countNum',$num);
		$this->display();
		}

	//购物车删除商品
	public function cart_del($id)
	{

		$uid = $_SESSION['id'];
		$cart = $this->shop_cart->where('id='.$id.' AND user_id='.$uid)->delete(); //删除该用户购物车的商品
		$this->redirect('user/mycart');
 		

	}
		

	//立即购买
	public function now_buy($id=''){
		C('LAYOUT_ON',false);
		$_SESSION['url']= $_SERVER['REQUEST_URI'];
		$uid = $_SESSION['id'];
        $product = $this->product->where('id='.$id)->select();//查找id在购物车上的商品

        $allPrice = ''; 							   //得出购物车上商品的总价
		foreach ($product as $val) {	
		 	$allPrice += $val['shop_price'];
		 } 

		 /*****第一次下单优惠*****/
		 $first = $this->order->where('uid='.$uid)->count();
		 if ($first==0) {
		 	if ($allPrice>=5000) {
		 		$sumRealPrice=$allPrice-500;
                $firstDeal="500";//满5000以上减去500	
		 	}elseif($allPrice>=3000&&$allPrice<5000){
		 		$sumRealPrice=$allPrice-200;
                $firstDeal="200";//满3000少于5000减去200
		 	}else{
		 		$sumRealPrice=$allPrice;
                $firstDeal="off";
		 	}
		 }else{
		 	$sumRealPrice=$allPrice;
            $firstDeal="off";
		 }

		$address=$this->address->where('uid='.$uid)->select();    //查看收货地址
		$coupon = D('coupon')->where('uid='.$uid)->select();
		$this->assign('coupon',$coupon);
		//标记
		$this->assign('sumRealPrice',$sumRealPrice);
		$this->assign('sumPrice',$allPrice);
		$this->assign('product',$product);
		$this->assign('address',$address);
		$this->display();
		
	}

	//加入购物车
	public function add_cart($id=''){
		$uid = $_SESSION['id'];
		$redo = $this->shop_cart->field('product_id')->where('user_id='.$uid)->select();
		$pid='';
		foreach ($redo as $val) {
			$pid.= implode('',$val).',';
		}
		$pid = explode(',',$pid);

		if (in_array($id,$pid)) {
			$this->redirect('product/item', array('id'=>$id,'ok'=>3));
		}else{
			$data = $this->product->where('id='.$id)->find();
			$arr['user_id'] = $uid;
			$arr['product_id'] = $data['id'];
			$arr['product_name'] = $data['name'];
			$arr['brand_id'] = $data['brand_id'];
			$arr['brand_name'] = $data['brand_name'];
			$arr['front_img'] = $data['front_img'];
			$arr['back_img'] = $data['back_img'];
			$arr['shop_price'] = $data['shop_price'];
			
			$cart = $this->shop_cart->add($arr);
			if ($cart) {
				$this->redirect('product/item', array('id'=>$id,'ok'=>1));
			}else{
				$this->redirect('product/item', array('id'=>$id,'ok'=>2));
			}
			
		}
		

	}
	//删除购物车中的商品
	public function del_cartProduct($id=''){
		$uid = $_SESSION['id'];
		$map['user_id&product_id'] =array($uid,$id,'_multi'=>true);
		$data = $this->shop_cart->where($map)->delete();
		$this->redirect('user/cart');
	}

	
	
/****************************临时测试*该页面要跳转到支付接口*********************************/
	public function add_order(){
		// p($_POST);
		// exit();
		$num=count($_POST['id']); // 计算出商品总数
		$ycode = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');
        $ordersn = $ycode[intval(date('y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
		$data['uid']=$_SESSION['id'];
        $data['order_num']=$ordersn;
        $data['sumNum']   = $num;  // 购买的商品数量
        $data['sum_price'] = $_POST['sumPrice']; //总价
        // $data['pay_type'] = $_POST['pay_type'];
        $addressID= $_POST['harvest'];  // 收获地址相关信息 的 ID
        # 通过addressID 查找对应的 收获联系方式
        $addressDate=$this->address->where('id='.$addressID)->find();

        $data['gid'] = $addressID;
        $data['gname'] = $addressDate['name'];
        $data['gtel']  = $addressDate['tel'];
        $data['address'] = $addressDate['province'].$addressDate['city'].$addressDate['zone'].$addressDate['address'];

        $arrId=$_POST['id'];      // 购买的一个或者多个商品的ID
        $productId=implode(",",$arrId);    //  格式化一下 产品ID
        $data['product_id']=$productId;
        $data['create_time']=time();
        $data['pay_type'] = 0;//默认支付方式为微信支付
        $reval=$this->order->add($data);
        if (!empty($_POST['card_id'])) {
            D('coupon')->where('id='.$_POST['card_id'])->delete();
        }
        $this->redirect("pay/weixinpay/?id=".$reval);
	}

/************************************购物车结束*******************************************/

/**************************************订单信息开始******************************************/
	
	
	//创建订单
	public function createorder(){
		C('LAYOUT_ON',false);
		$_SESSION['url']= $_SERVER['REQUEST_URI'];
		$uid = $_SESSION['id'];
		$p_id = empty($_GET['id'])?implode(",",$_POST['id']):$_GET['id'];
		//所有支付ID格式化为字符串
		$map['id']  = array('in',$p_id);
        $product = $this->product->where($map)->select();//查找id在购物车上的商品

        $allPrice = ''; 							   //得出购物车上商品的总价
		foreach ($product as $val) {	
		 	$allPrice += $val['shop_price'];
		 } 

		 /*****第一次下单优惠*****/
		 $first = $this->order->where('uid='.$uid)->count();
		 if ($first==0) {
		 	if ($allPrice>=5000) {
		 		$sumRealPrice=$allPrice-500;
                $firstDeal="500";//满5000以上减去500	
		 	}elseif($allPrice>=3000&&$allPrice<5000){
		 		$sumRealPrice=$allPrice-200;
                $firstDeal="200";//满3000少于5000减去200
		 	}else{
		 		$sumRealPrice=$allPrice;
                $firstDeal="off";
		 	}
		 }else{
		 	$sumRealPrice=$allPrice;
            $firstDeal="off";
		 }

		$address=$this->address->where('uid='.$uid)->select();    //查看收货地址
		$coupon = D('coupon')->where('uid='.$uid)->select();
		$this->assign('productId',$p_id);
		$this->assign('coupon',$coupon);
		$this->assign('sumRealPrice',$sumRealPrice);
		$this->assign('sumPrice',$allPrice);
		$this->assign('product',$product);
		$this->assign('address',$address);
		$this->display();
	}


	//订单展示页
	public function order()
	{
		C('LAYOUT_ON',false);
		//这是待付款的
		$_SESSION['url']= $_SERVER['REQUEST_URI'];
		$map1['uid'] = $_SESSION['id'];
		$map1['is_display'] = 0;
		$map1['is_pay'] = 0;
		$map1['is_send'] = 0;
		$map1['is_accept'] = 0;
		// $map1['pay_trade_status'] = "";
		$map1['pay_trade_status'] = array('neq',"TRADE_CLOSED");
      	$data1 =$this->order->where($map1)->order('create_time desc')->select();
     	foreach ($data1 as &$val) {
			$val['a'] = explode(',',$val['product_id']);
			$val['count'] = count($val['a']);
			$val['arr']=array();
			foreach($val['a'] as $v){
    		    $val['arr'][] = $this->product->where('id='.$v)->find();
   			 }
		}
		

		//这是待发货的

		$map2['uid'] = $_SESSION['id'];
		$map2['is_display'] = 0;
		$map2['is_pay'] = 1;
		$map2['is_send'] = 0;
		$map2['is_accept'] = 0;
		// $map2['pay_trade_status'] = array(array('eq','20'), 'or') ;
      	$data2 =$this->order->where($map2)->order('create_time desc')->select();
     	foreach ($data2 as &$val) {
			$val['a'] = explode(',',$val['product_id']);
			$val['count'] = count($val['a']);
			$val['arr']=array();
			foreach($val['a'] as $v){
    		    $val['arr'][] = $this->product->where('id='.$v)->find();
   			 }
		}

		//这是待收货的

		$map3['uid'] = $_SESSION['id'];
		$map3['is_display'] = 0;
		$map3['is_pay'] = 2;
		$map3['is_send'] = 1;
		$map3['is_accept'] = 0;
		// $map3['pay_trade_status'] = 'WAIT_BUYER_CONFIRM_GOODS';
      	$data3 =$this->order->where($map3)->order('create_time desc')->select();
     	foreach ($data3 as &$val) {
			$val['a'] = explode(',',$val['product_id']);
			$val['count'] = count($val['a']);
			$val['arr']=array();
			foreach($val['a'] as $v){
    		    $val['arr'][] = $this->product->where('id='.$v)->find();
   			 }
		}

		//这是完成交易的

		$map4['uid'] = $_SESSION['id'];
		$map4['is_display'] = 0;
// $ord.pay_trade_status neq TRADE_CLOSED)AND($ord.is_accept eq 1)
		// $map4['is_pay'] = 0;
		// $map4['is_send'] = 1;
		// $map4['is_accept'] = 1;
		// $map4['pay_trade_status'] = array('eq','');
		// $map4['pay_trade_status'] = array(array('eq', 'TRADE_FINISHED'),array('eq','20'),array('eq', 'TRADE_CLOSED'), 'or');
      	$data4 =$this->order->where($map4)->order('create_time desc')->select();
     	foreach ($data4 as &$val) {
			$val['a'] = explode(',',$val['product_id']);
			$val['count'] = count($val['a']);
			$val['arr']=array();
			foreach($val['a'] as $v){
    		    $val['arr'][] = $this->product->where('id='.$v)->find();
   			 }
		}

		// p($data1);
		// p($data2);
		// p($data3);
		// p($data4);
		$idx = $_GET['idx'];
		$this->assign('data1',$data1);	
		$this->assign('data2',$data2);
		$this->assign('data3',$data3);
		$this->assign('data4',$data4);
		$this->assign('idx',$idx);
		$this->display();
	}

	//订单详情
	public function orderdes($id)
	{
		C('LAYOUT_ON',false);
		$order = $this->order->where('id='.$id)->find();
		$p_id = explode(',', $order['product_id']);
		$num = count($p_id);//订单商品数量
		$map['id'] = array('in',$order['product_id']);
		$product = $this->product->where($map)->select();//订单中的商品
		$address = $this->address->where('id='.$order['gid'])->find();//订单中的收货地址
		
		$this->assign('num',$num);
		$this->assign('product',$product);
		$this->assign('address',$address);
		$this->assign('order',$order);
		$this->display();
	}



	//收货
	public function orderOK(){
			$id = $_POST['id'];
		// $ord = $this->order->where('id='.$id)->find();
		// if (!empty($ord)) {
			$arr = array('pay_trade_status'=>'TRADE_FINISHED','is_pay'=>3,'is_accept'=>1,'accept_time'=>date('Y-m-d H:i:s',time()));
			$data = $this->order->where('id='.$id)->save($arr);
			echo !empty($data)?'{"status":"success","message":"您已确认收货！"}':'{"status":"error","message":"您收货失败，请联系客服！"}'; 
		// }else{

		// }
		

		


	}


	//网银确认收货
	public function order_ok($id){
		$arr = array('pay_trade_status'=>'TRADE_FINISHED','is_pay'=>3,'is_accept'=>1,'accept_time'=>date('Y-m-d H:i:s',time()));
		$data = $this->order->where('id='.$_GET['id'])->save($arr);
		if ($data) {
			$this->redirect('user/order',array('ok'=>1));
		}else{
			$this->redirect('user/order',array('ok'=>2));
		}
	}
	
	//支付订单
	public function payorder($id)
	{
		C('LAYOUT_ON',false);
		$order = $this->order->where('id='.$id)->find();
		$p_id = explode(',', $order['product_id']);
		$num = count($p_id);//订单商品数量
		
		$this->assign('num',$num);
		$this->assign('order',$order);
		$this->display();
	}


	//订单删除
	public function del_order(){
		$order = $this->order->where('uid='.$_SESSION['id'])->find();
		// echo '{"status":"'.$_POST['id'].'","massige":"删除成功！"}';
		// exit();
		if (!empty($order)) {
			$this->order->where('id='.$_POST['id'])->setField("is_display",1);
			echo '{"status":"success","massige":"删除成功！"}';
			exit();
			// $this->redirect("User/user_order");
		}else{
			echo '{"status":"error","massige":"删除失败！"}';
			exit();
		}
		 
	}

/**************************************订单信息结束******************************************/

/***************************************寄卖信息开始*****************************************/

	function mycons()
	{
		C('LAYOUT_ON',false);
		$_SESSION['url']= $_SERVER['REQUEST_URI'];
		//所有寄卖商品
		$map['user_id&is_del'] =array($_SESSION['id'],array('EQ','0'),'_multi'=>true);
		$consign = $this->consign->where($map)->order('ltime desc')->select();
		foreach ($consign as &$val) {
			$val['time'] = date('Y-m-d H:i',$val['ltime']);
			$val['img'] = $this->consign_img->where(array('pid'=>$val['id']))->getField('path');
			$val['product_id'] = $this->product->where(array('consign_id'=>$val['id']))->getField('id');
		}
		//审核中
		$map1['user_id&is_del&is_pass'] =array($_SESSION['id'],array('EQ','0'),array('NEQ','3'),'_multi'=>true);
		$consign1 = $this->consign->where($map1)->order('ltime desc')->select();
		foreach ($consign1 as &$val) {
			$val['time'] = date('Y-m-d H:i',$val['ltime']);
			$val['img'] = $this->consign_img->where(array('pid'=>$val['id']))->getField('path');
			$val['product_id'] = $this->product->where(array('consign_id'=>$val['id']))->getField('id');
		}


		//正在寄卖的商品
		$arr = array('uid'=>$_SESSION['id'],'stock'=>0,'is_sale'=>0); 
		$consign2 = $this->product->where($arr)->order('set_time desc')->select();
		foreach ($consign2 as $key => &$val) {
		    $vo['id&is_del&is_pass'] =array($val['consign_id'],array('EQ','0'),array('EQ','3'),'_multi'=>true);
			$val['con'] = $this->consign->where($vo)->find();
		   
		}

		// $map2['user_id&is_del&is_pass'] =array($_SESSION['id'],array('EQ','0'),array('EQ','3'),'_multi'=>true);
		// $consign2 = $this->consign->where($map2)->order('id desc')->select();
		// foreach ($consign2 as &$val) {
		// 	$val['time'] = date('Y-m-d H:i',$val['ltime']);
		// 	$val['img'] = $this->consign_img->where(array('pid'=>$val['id']))->getField('path');
		// 	$val['product_id'] = $this->product->where(array('consign_id'=>$val['id']))->getField('id');
		// }
		
		//已经售出的商品
		$arr = array('uid'=>$_SESSION['id'],'stock'=>2); 
		$consign3 = $this->product->where($arr)->order('set_time desc')->select();

		foreach ($consign3 as $key => &$val) {
		    $map3['id&is_del&is_pass'] =array($val['consign_id'],array('EQ','0'),array('EQ','3'),'_multi'=>true);
			$val['con'] = $this->consign->where($map3)->find();
		   
		}
		
		$idx = $_GET['idx'];
		$this->assign('consign',$consign);
		$this->assign('consign1',$consign1);
		$this->assign('consign2',$consign2);
		$this->assign('consign3',$consign3);
		$this->assign('idx',$idx);
		$this->display();
	}	
	


	//下架图片寄卖商品
	public function sold_out(){
		
		$arr = array('is_pass'=>3,'is_del'=>2,'out_time'=>date('Y-m-d H:i:s',time()));
		$this->consign->where(array('id'=>$_GET['id']))->setField($arr);
		$this->consign_img->where(array('pid'=>$_GET['id']))->setField('is_del',1);
		$this->product->where('consign_id='.$_GET['id'])->setField('is_sale',1);
		$idx = $_GET['idx'];
		if ($idx==2) {
			$this->redirect('user/mycons/?idx=2');
		}elseif($idx==3){
			$this->redirect('user/mycons/?idx=3');
		};
		
		
	}

	//发布寄卖商品
	public function addcons(){
		$arr = array('is_pass'=>3,'is_del'=>0,'out_time'=>date('Y-m-d H:i:s',time()));
		$data =$this->consign->where(array('id'=>$_GET['id']))->setField($arr);
		if($data){
			$this->consign_img->where(array('pid'=>$_GET['id']))->setField('is_del',0);
			$this->product->where('consign_id='.$_GET['id'])->setField('is_sale',0);
			$this->redirect('user/mycons/?idx=3');
		}else{
			$this->redirect('user/mycons');
		}
	}

/***************************************寄卖信息结束*****************************************/

/***************************************个人收藏开始***************************************/
	
	public function wish()
	{
		C('LAYOUT_ON',false);
        $user_id=$_SESSION['id'];
        $data=$this->favorite->where('user_id='.$user_id)->order('id')->select();
		//查找出产品的等级
        foreach($data as &$vo)
        {
            $aa = $this->product->field('id','plevel','stock')->where('id='.$vo['product_id'])->find();
            $vo['plevel']=$aa['plevel'];//商品等级
            $vo['stock']=$aa['stock'];//商品状态

        }
        $this->assign('id',$user_id);
        $this->assign('data',$data);
		$this->display();
	}

	public function delFavorite($id)          //  删除收藏的信息
    {
    	
       $data = $this->favorite->where('id='.$id)->delete();
       if($data){
       		$this->redirect('user/wish');
       }else{
       		$this->redirect('user/wish');
       }
       exit;
        // $this->redirect("user/wish");
    }


    public function see_More()
    {

        $user_id=$_SESSION['id'];
        $count=$_POST['start'];
        $seeProduct = $this->favorite->where('user_id='.$user_id)->limit($count.",4")->order('id')->select();

        $str="";
        foreach($seeProduct as $r)
        {
            $str.="<div class='wish-item' id='wish{$r['id']}'>
					<a class='wish-item-img' href='/HomePhone/product/item/id/{$r['product_id']}.html'>
						<div>
							<img src='/APP/Public/upload/{$r['front_img']}?".time()."' />
						</div>
					</a>
					<div class='wish-item-des'>
						<div>￥{$r['shop_price']}</div>
						<div>{$r['brand_name']}</div>
						<div>{$r['product_name']}</div>
					</div>
					<div class='wish-item-lv'>
						<img src='/APP/Modules/HomePhone/Public/image/lv-s.png'/>
					</div>
					<a class='wish-item-del' style='cursor:pointer' onclick='ajaxdel({$r['id']})' data-js='{:U('user/delFavorite')}'>
						<img src='/APP/Modules/HomePhone/Public/image/del.png'/>
					</a>
				</div>";
        }

        print_r($str);
        exit;
    }

/***************************************个人收藏结束***************************************/
	
/*************************************实名认证开始***************************************/
	function real()
	{
		C('LAYOUT_ON',false);
		
		$data = $this->user->where('id='.$_SESSION['id'])->select();
		$this->assign('data',$data[0]);
		
		$this->display();
	}


	//实名认证处理
	public function do_real()
	{
		;
		//通过实名认证那么rel==1
	if ($_POST['name']!=''||$_POST['name']!=null) {
		// $this->redirect('user/real', array('ok'=>7));
		if($_POST['idcard']==$_POST['reidcard']){
			$data = (preg_match("/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/",$_POST['idcard']))?1:0;
			if ($data==0) {
				$this->redirect('user/real');
				// $this->error('您的身份证号有误，请重新填写！');
			}else{
				$rel=$this->user->where(array('id'=>$_SESSION['id']))->getField('rel');
				if($rel==1){
					$this->redirect('user/real');
					// $this->success('您已经提交了实名认证！无需再次认证!
				}elseif($rel==3){
						if($_FILES){
							//添加图片
							$id = $_SESSION['id'];
							/*********************将旧文件删除************************/
							$img = D('real')->where('uid='.$id)->select();
							foreach ($img as $val) {
								$files = APP_PATH.'Public/Real/'.$val['back'];
								unlink($files);//删除旧文件
								D('real')->where('id='.$val['id'])->delete();
								
							}
             				/*********************将旧文件删除************************/
							
							$a = $this->commitImg($id);
							if ($a) {
								$arr = array('name'=>$_POST['name'],'idcard'=>$_POST['idcard'],'rel'=>2,'ctime'=>date('Y-m-d H:i:s',time()));
								$this->user->where(array('id'=>$_SESSION['id']))->setField($arr);

								/*******************邮箱提示有用户申请审核************************/
									 $sendName = "流奢网用户实名认证申请";//邮件标题
									 $body = "流奢网有用户正在申请实名认证。";//邮件内容
									 $url = "http://www.rexury.com/Admin";//邮箱跳转地址
									 $this->emailsend($sendName,$body,$url);
								$this->redirect('user/real');
								// $this->success("我们将在2-5个工作日以内完成审核，届时您将可以在我站寄卖商品了！",U('User/user_real'));
							}else{
								$this->redirect('user/real');
								// $this->error('请上传您的证件照！');
							}
						}else{
							$this->redirect('user/real');
							// $this->error('请上传您的证件照！');
						}
						
					}elseif($rel==0){
						if($_FILES){
						//添加图片
							$id = $_SESSION['id'];
							$a = $this->commitImg($id);
							if ($a) {
								$arr = array('name'=>$_POST['name'],'idcard'=>$_POST['idcard'],'rel'=>2,'ctime'=>date('Y-m-d H:i:s',time()));
								$this->user->where(array('id'=>$_SESSION['id']))->setField($arr);

								/*******************邮箱提示有用户申请审核************************/
									
									 $sendName = "流奢网用户实名认证申请";//邮件标题
									 $body = "流奢网有用户正在申请实名认证。";//邮件内容
									 $url = "http://www.rexury.com/Admin";//邮箱跳转地址
									 $this->emailsend($sendName,$body,$url);

								$this->redirect('user/real');
							}else{
								$this->redirect('user/real');
								// $this->error('请上传您的证件照！');
							}
						}else{
							$this->redirect('user/real');
							// $this->error('请上传您的证件照！');
						}
					}
				}	
			}else{
				$this->redirect('user/real');
			// $this->error('您输入的身份证号码不一致，请确认后再重新填写！');
			}
		}else{
			$this->redirect('user/real');
		}
	}



	
	
	//上传图片方法
	public function commitImg($id='')
    {
    	$real=D('real');
        import('ORG.Net.UploadFile');
        $upload = new UploadFile();// 实例化上传类
        $upload->maxSize  = 5000000 ;// 设置附件上传大小
        $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->savePath =  APP_PATH.'Public/Real/'.date('Ymd').'/';// 设置附件上传目录
        $data['uid']=$id;
        if($upload->upload()) {// 上传错误提示错误信息
            $info =  $upload->getUploadFileInfo();
          }
        foreach($info as $val)
        {
            $data['front']=$val['name'];
            $data['back'] = date('Ymd').'/'.$val['savename'];
            $e=$real->add($data);
        }
        return $e;
    }

	/*************************************实名认证结束***************************************/


	/*************************************用户个人钱包开始**************************************/
	public function wallet(){
		if (IS_POST) {
			if ( $_POST['status'] == 0 )//验证是否有密码
			{
				$pass = $this->wallet->where('uid='.$_SESSION['id'])->getField('password');
				$haskey = empty($pass) ? 0 : 1;
				echo '{"haskey":"'.$haskey.'"}';
			}
			else if ( $_POST['status'] == 1 )//添加密码
			{
				$add_pass = $this->wallet->where('uid='.$_SESSION['id'])->setField('password',md5($_POST['key']));
				$success = empty($add_pass) ? 0 : 1;
				echo '{"success":"'.$success.'"}';
			}
			else if ( $_POST['status'] == 2 )//提交提现单
			{
				$key = $this->wallet->where('uid='.$_SESSION['id'])->getField('password');
				if ( md5($_POST['key']) != $key )
				{
					echo '{"status":"0"}';
					exit();
				}
				$money = $this->wallet->where('uid='.$_SESSION['id'])->getField('money');
				$post_money = intval($_POST['count']);
				$des = $money - $post_money;

				if ( $des < 0 )
				{
					echo '{"status":"1"}';
					exit();
				}
				$this->wallet->where('uid='.$_SESSION['id'])->setField('money',$des);
				$pid = $this->wallet->where('uid='.$_SESSION['id'])->getField('id');
				$trans = array('pid'=>$pid,'date'=>date('Y-m-d H:i:s',time()),'balance'=>$money,'account'=>$_POST['alipay'],'nick'=>$_POST['nick'],'money'=>$post_money,'status'=>0);
				$transfer = $this->transfer->add($trans);
				if ($transfer) {
					/************向网站管理人员发送提醒邮件*****************/
					 $sendName = "流奢网用户提现申请";
					 $body = "流奢网有用户需要提现。";
					 $url = "http://www.rexury.com/Admin";
					 $this->emailsend($sendName,$body,$url);
					 /***********向网站管理人员发送提醒邮件*****************/
					
	   				 echo '{"status":"2"}';
				}
			}
		}else{
			C('LAYOUT_ON',false);
			$u_wallet = $this->wallet->where('uid='.$_SESSION['id'])->find();
			if (empty($u_wallet)) { 
				$arr = array('uid' => $_SESSION['id'],'ltime'=>date('Y-m-d H:i:s',time()),'money'=>0);
				$this->wallet->add($arr);
			}else{
				$money = $this->wallet->where('uid='.$_SESSION['id'])->getField('money');
			}
			$this->assign('money',$money);
			$this->display();
		}

	}
	//发送邮件方法
	public function emailsend($sendName,$body,$url){
		 $config = C('THINK_EMAIL');
		 $emailtype = "HTML"; //信件类型，文本:text；网页：HTML
		 $to = $config['USER_EMAIL'];
		 $from = $config['FROM_EMAIL'];
		 $emailsubject = $sendName;
		 $emailbody = "亲爱的".$to."：<br/>".$body."<br/>请登陆网站后台及时处理。<br/><a href='".$url."' target='_blank'>".$url."</a>				<br/>如果以上链接无法点击，请将它复制到你的浏览器地址栏中进入访问，该链接24小时内有效。<br/>				如果此次激活请求非你本人所发，请忽略本邮件。<br/><p style='text-align:right'>-------- www.rexury.com 敬上</p>";
		 $rs = think_send_mail($to, $from, $emailsubject, $emailbody, $emailtype);
	   				 // $rs = think_send_mail('要发送的邮箱','发送人名称，即你的名称','文件标题','邮件内容');
	}
	/*************************************用户个人钱包结束**************************************/



	/**************************************地址信息开始*************************************/
	//地址详情展示页面
	function address()
	{
		
		C('LAYOUT_ON',false);
		 $address=$this->address->where('uid='.$_SESSION['id'])->order(array('default'=>'desc'))->select();
         $this->assign("address",$address);
         $this->display();
		
	}
	//地址添加处理
	public function add_address(){
		
        $count = $this->address->where('uid='.$_SESSION['id'])->count();

	    $data['default'] = $count < 1 ? 1 : 0;
	    $data['name'] = $_POST['name'];
	    $data['province'] = $_POST['province'];
	    $data['city'] = $_POST['city'];
	    $data['zone'] = $_POST['zone'];
	    $data['address'] = $_POST['address'];
	    $data['tel'] = $_POST['tel'];
	    $data['uid'] = $_SESSION['id'];
	    $id = $this->address->add($data);

		echo '{"status":"success","message":"地址添加成功！","id":"'.$id.'"}';
        // if ($_POST['page']=='cart') {//如果是从创建订单 传过来的那么跳回创建订单
        //     $this->redirect("user/createorder");
        // }
        // $this->redirect("user/address");
	}
	//删除地址
	public function del_address()
    {
    	
    	$arr = array('id'=>$_POST['id'],'uid'=>$_SESSION['id']);
    	$default = $this->address->where($arr)->getField('default');
    	if ($default = 1) {//如果删除的是默认的   那么将下一个设为默认
    		$this->address->where($arr)->delete();
    		$data =  $this->address->where($arr)->find();
        	$this->address->where('id='.$data['id'])->setField('default',1);
    		echo '{"status":"success"}';
    	}else{
    		$this->address->where($arr)->delete();
    		echo '{"status":"success"}';
    	}
         
    }
    //设为默认地址
    public function address_default(){
		$data = $this->address->where('uid='.$_SESSION['id'])->setField('default',0);
		$this->address->where('id='.$_GET['id'])->setField('default',1);
		$this->redirect('user/address');
		
	}
	//修改地址
	public function set_address()
    {
    	
    	if ($_POST['on']==1) {
		//如果有default传过来，那么将此人ID下的所有地址设为default=0；
			$this->address->where('uid='.$_SESSION['id'])->setField('default',0);
        	$data['default'] = $_POST['on'];
        }
	    $data['name'] = $_POST['name'];
	    $data['province'] = $_POST['province'];
	    $data['city'] = $_POST['city'];
	    $data['zone'] = $_POST['zone'];
	    $data['address'] = $_POST['address'];
	    $data['tel'] = $_POST['tel'];
	    // $data['uid']=$_SESSION['id'];
	  	$this->address->where("id=".$_POST['id'])->save($data);
        echo '{"proID":"'.$_POST['proID'].'","message":"修改成功！"}';
            
    }
/**************************************地址信息结束*************************************/

/************************************账户信息开始***************************************/
	function bank()
	{
		C('LAYOUT_ON',false);
		$data = $this->bank->where('uid='.$_SESSION['id'])->order(array('default'=>'desc'))->select();
		foreach ($data as &$val) {
			$val['name'] = $this->user->where('id='.$_SESSION['id'])->getField('name');
			}
		$name = $this->user->where('id='.$_SESSION['id'])->getField('name');
		$this->assign('name',$name);
		$this->assign('bank',$data);
		$this->display();
		
	}

	//添加支付账号
	public function add_bank(){
		$uid = $_SESSION['id'];
		$type = $_POST['type'];
		$banks = $_POST['bank'];
		$bank_address = $_POST['bank_address'];
		$bank_card = $_POST['bank_card'];
		$name = $_POST['name'];
		if ($type==0||$type=='') {
			$bank['uid'] = $uid;
			$bank['type'] = $type;
			$bank['bank'] = $banks;
			$bank['bank_address'] = $bank_address;
			$bank['bank_card'] = $bank_card;
			if($name==$this->user->where('id='.$uid)->getField('name')){
				$data = $this->bank->add($bank);
				if($data){
					echo '{"status":"success", "message":"添加成功！"}';
				}else{
					echo '{"status":"error", "message":"添加失败！"}';
				}	
			}else{
				 echo '{"status":"error", "message":"添加失败！"}';
			}
		}elseif($_POST['type']==1){
			$zfb['uid'] = $uid;
			$zfb['type'] = $type;
			$zfb['zfb_num'] = $bank_card;
			if($name==$this->user->where('id='.$zfb['uid'])->getField('name')){
				$data = $this->bank->add($zfb);
				if($data){
					echo '{"status":"success", "message":"添加成功！"}';
				}else{
					echo '{"status":"error", "message":"添加失败！"}';
				}
			}else{
				 	echo '{"status":"error", "message":"添加失败！"}';
				
			}
		}
	}
	//删除账户
	public function del_bank(){
		$getid=$_GET['id'];//获取选择的复选框的值
			if (!$getid) $this->error('未选择记录') ;//没选择就提示信息
			   //选择一个以上，就用,把值连接起来(1,2,3)这样		
			$Result=$this->bank->where('id='.$getid)->delete();
			if($Result===false){
				$this->error('操作失败');
			}else{
	        	$this->redirect('user/bank');
			}
	}
	//设置默认账户
	public function bank_default(){
		$this->bank->where('uid='.$_SESSION['id'])->setField('default',0);
		$this->bank->where('id='.$_GET['id'])->setField('default',1);
		$this->redirect('user/bank');
	}
/************************************账户信息结束***************************************/

/************************************修改密码开始*****************************************/	
	function password()
	{
		C('LAYOUT_ON',false);
		$this->display();
	}

	//处理修改密码
	public function set_password()
	{
		$password = MD5($_POST['password']);
		$newpass = MD5($_POST['newpass']);
		$id = $_SESSION['id'];
		$data = $this->user->where('id='.$id)->find();
		if ($data['password']!==$password) {
			echo '{"status":"error", "message":"您的旧密码不符，请重新输入！"}'; 
		}else{
			$set = $this->user->where('id='.$id)->setField('password',$newpass);
			if ($set) {
				echo '{"status":"success", "message":"恭喜您，您的密码修改成功！"}'; 
			}else{
				echo '{"status":"success", "message":"您没有修改您的密码，请继续使用旧密码！"}'; 
			}
		}
		
		
	}
/************************************修改密码结束*****************************************/	

/*************************************地址三级联动**************************************/
	function address_select()
    {
        $condition=$_POST['condition'];
        $type=$_POST['type'];
        echo "<option value='0' selected=true>-请选择-</option>";
        switch($type)
        {
            case "province":

                $tran=$this->diqudaima->province();

                foreach ($tran as $v) {

                    echo $str = "<option value=" . $v['province'] . ">" . $v['province'] . "</option>";
                }
                break;

            case "city":

                $tran=$this->diqudaima->city($condition);
                foreach ($tran as $v) {

                    echo $str = "<option value=" . $v['city'] . ">" . $v['city'] . "</option>";
                }
                break;

            case "zone":
                $tran=$this->diqudaima->zone($condition);

                foreach ($tran as $v) {

                    echo $str = "<option value=" . $v['zone'] . ">" . $v['zone'] . "</option>";
                }
                break;
        }
    }

    /*******微信登录******/

    public function setWxPass(){
        $id=$_SESSION['id'];
        if(!empty($_POST['passTwo']))
        {
            $data['password']=md5($_POST['passTwo']);
            D("user")->where('id='.$id)->save($data);
            $this->redirect('user/center');
        }
        else
        {
            echo "请在网站范围内注册!!!";
            exit;
        }
    }
	
    /*******修改资料******/	
	public function edit(){
		if (IS_POST) {
			// p($_POST);
			$this->user->where('id='.$_SESSION['id'])->setField("nick",$_POST['nick']);
			
			if($_FILES['pic']['error']==0){
				$this->upload_pic($_SESSION['id']);
			}
			$this->redirect('user/edit');
			
		}
		C('LAYOUT_ON',false);
		$user=$this->user->where('id='.$_SESSION['id'])->find();
		$this->assign("user",$user);
		$this->display();
	}

	public function upload_pic($uid){
		
			//处理上传
			/*********************将旧文件删除************************/
			$img = $this->user->where('id='.$uid)->getField('head_pic');
			$files = APP_PATH.'Public/User_pic/'.$img;
			unlink($files);//删除旧文件
			/*********************将旧文件删除************************/
			//加载上传类
			import('ORG.Net.UploadFile');
			//实例化上传类
			$upload = new UploadFile();
			//进行设置
			$upload->allowExts = array('jpg','gif','png','jpeg');
			$upload->savePath = APP_PATH.'Public/User_pic/';
			//执行上传
			if ($upload->upload()) {
				$info = $upload->getUploadFileInfo();
				$data['head_pic'] = $info[0]['savename'];
				$pic = $this->user->where(array('id'=>$uid))->save($data); // 写入用户数据到数据库

			}

		return $pic;
	}
	
	
/*************************************地址三级联动**************************************/
    //测试AJAX用的test
     public function test(){
     	echo json_decode($_POST);
     	exit();
        if($_POST){
             echo '{"status":"success", "message":"'.$_POST['name'].'"}';
        }else{
            echo '{"status":"300", "message":"登录失败"}';
        }
       
            
      
    }
	
	//编辑收货地址
	public function form(){
		if(IS_POST){
			p($_POST);
			exit();
		}else{
			C('LAYOUT_ON',false);
			$data = $this->address->where('uid='.$_SESSION['id'])->select();
			$this->assign('address',$data);
			$this->display();

		}
	}
	
}